﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace AisinGioro.Server
{
    using Core;
    using Core.WinForm;
    using Notify;

    public partial class MainForm : Form
    {
        MaskLoading _maskLoading;
        ServerManager _server = null;
        NetworkInfo _ni = null;
        INotify _notify = null;

        public MainForm()
        {
            _ni = new NetworkInfo();
            _notify = NotifyBase.GetInstance();

            InitializeComponent();
            
            this.Controls.Add(_maskLoading = new MaskLoading());
            var ipList = _ni.GetLocalIpList();
            ipList.Insert(0, "*");
            this.cbxIPAddresses.DataSource = ipList;
        }
        
        private void MainForm_Load(object sender, EventArgs e)
        {
            
        }

        #region 开启/停止主机服务
        private void btnStart_Click(object sender, EventArgs e)
        {
            var hostUrl = $"http://{this.cbxIPAddresses.SelectedValue}:{this.nmrPort.Value}";
            if (_server == null)
            {
                _server = new ServerManager(hostUrl);
                _server.OnStartSucceed += _server_OnStartSucceed;
                _server.OnStopSucceed += _server_OnStopSucceed;
                _server.OnFailed += _server_OnFailed;
            }

            _server.Start();
            _maskLoading.ShowLoad();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_server != null)
                _server.Stop();
                        
            //主机Stop后再Start，客户端重新连接总是超时，还未想到解决办法，先暂时重启应用程序解决
            Application.ExitThread();
            Application.Restart();
        }

        private void _server_OnStartSucceed(object sender, EventArgs e)
        {
            WinFormHelper.SetControlCrossThread(this.Container1, () =>
            {
                this.btnStart.Enabled = false;
                this.btnStop.Enabled = true;
                this.cbxIPAddresses.Enabled = false;
                this.nmrPort.Enabled = false;
                _maskLoading.HideLoad();
            });

            MessageBox.Show("Server started! " + _server.HostUrl);

            //服务器开启成功后，开始轮询当前所有在线主机（检查最后响应时间是否过期）
            _server.PollingAliveAgents();
            
            //服务器开启成功后，开始循环推送 Monitor 信息（PING,PORT,HTTP）
            _server.PollingMonitors();
        }

        private void _server_OnStopSucceed(object sender, EventArgs e)
        {
            WinFormHelper.SetControlCrossThread(this.Container1, () =>
            {
                this.btnStart.Enabled = true;
                this.btnStop.Enabled = false;
                this.cbxIPAddresses.Enabled = true;
                this.nmrPort.Enabled = true;
                _maskLoading.HideLoad();
            });
                        
            //MessageBox.Show("Server stopped!");
        }

        private void _server_OnFailed(object sender, ErrorOccuredEventArgs e)
        {
            WinFormHelper.SetControlCrossThread(_maskLoading, () =>
            {
                _maskLoading.HideLoad();
            });
            
            MessageBox.Show(e.Error.Message, "Error");
        }
        #endregion

        #region 标题栏拖动
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wparam, int lparam);
        private void menuStrip1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //按下的是鼠标左键
            {
                Capture = false; //释放鼠标使能够手动操作
                SendMessage(Handle, 0x00A1, 2, 0); //拖动窗体
            }
        }
        #endregion        

        #region 窗体显示状态控制
        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //this.ContextMenuStrip.Show(Cursor.Position.X, Cursor.Position.Y);
            this.toolStripMenuItemOpen_Click(this.toolStripMenuItemOpen, e);
        }

        private void toolStripMenuItemOpen_Click(object sender, EventArgs e)
        {
            this.ShowInTaskbar = true;  //显示在系统任务栏
            this.WindowState = FormWindowState.Normal;  //还原窗体
            this.BringToFront();
            //notifyIcon.Visible = false;  //托盘图标隐藏
        }

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            this.btnFormClose_Click(this.btnFormClose, EventArgs.Empty);
        }

        private void btnFormHidden_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
        }

        private void btnFormClose_Click(object sender, EventArgs e)
        {
            if (_server != null)
                _server.Stop();

            this.notifyIcon.Visible = false;
            this.Close();
            this.Dispose();
            Environment.Exit(Environment.ExitCode);
        }
        #endregion
    }
}
